﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Xodeuz.SP.Common
{
    public class ReflectionService
    {
        public static IEnumerable<PropertyInfo> PublicPropertyInfos(Type type)
        {
            return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
        }

        public static PropertyInfo GetPropertyInfoByName(Type t, String name)
        {
            return PublicPropertyInfos(t).FirstOrDefault(prop => prop.Name == name);
        }

        public static IEnumerable<ContentType> GetContentTypes(Type _type)
        {
            var results = _type.GetCustomAttributes(typeof(ContentType), true);

            return results.Length != 0 ? results.Cast<ContentType>().ToArray() : new ContentType[0];
        }

        public static object GetListCreationInformation(Type type)
        {
            return type.GetCustomAttributes(typeof(SharePointList), true).FirstOrDefault();
        }


        public static Dictionary<string, FieldCreation> GetFieldCreations(Type type)
        {
            var properties = PublicPropertyInfos(type);
            var mapping = new Dictionary<String, FieldCreation>();

            foreach (PropertyInfo p in properties)
            {
                Field fieldInfo = p.GetCustomAttributes(typeof(Field), true).FirstOrDefault() as Field;

                if (fieldInfo == null) continue;

                if (ReadOnly.CreationFields.Contains(fieldInfo.InternalName)) continue;

                mapping.Add(p.Name, new FieldCreation
                {
                    InternalName = fieldInfo.InternalName,
                    Type = fieldInfo.FieldType,
                    DisplayName = String.IsNullOrEmpty(fieldInfo.DisplayName) ? fieldInfo.InternalName : fieldInfo.DisplayName
                });
            }

            return mapping;
        }

        public static Dictionary<string, T> GetPropertyNameWithCustomAttribute<T>(Type origin)
        {
            var properties = PublicPropertyInfos(origin);
            var mapping = new Dictionary<string, T>();

            foreach (PropertyInfo p in properties)
            {
                var customAttributes = p.GetCustomAttributes(typeof(T), true);

                if (customAttributes.Length == 0) continue;
                var attr = customAttributes.FirstOrDefault();

                if (attr != null)
                    mapping.Add(p.Name, (T)attr);
            }

            return mapping;
        }

        internal static object GetListDefinitionAttribute(Type type)
        {
            return type.GetCustomAttributes(typeof(SharePointList), true).FirstOrDefault();
        }
    }
}
